! This file is part of ti-sph. All rights reserved.
!! 利用 ESC 码和环境变量设置终端颜色

!> author: 左志华
!> date: 2022-07-14
!> version: beta
!>
!> 终端文本，给出带样式的终端文字，更友好的用户 CLI 界面
!> @note 手动设置环境变量 NO_COLOR=1 可以关闭终端文本样式
module sph_terminal

    use seakeeping_utils, only: optenv
    use seakeeping_string, only: string_t

    type(string_t) :: color(5)  !! 红、绿、黄、蓝，无
    character(*), parameter :: colors(*) = [achar(27)//'[31m', &
                                            achar(27)//'[32m', &
                                            achar(27)//'[33m', &
                                            achar(27)//'[34m', &
                                            achar(27)//'[00m']

contains

    !> 根据 NO_COLOR 环境变量，启用控制台颜色
    subroutine set_terminal(use_color)
        logical, intent(in) :: use_color  !! 是否启用颜色

        if (len(optenv('NO_COLOR', '')) == 0 .and. use_color) then
            color(1)%raw = colors(1)
            color(2)%raw = colors(2)
            color(3)%raw = colors(3)
            color(4)%raw = colors(4)
            color(5)%raw = colors(5)
        else
            color(1)%raw = ''
            color(2)%raw = ''
            color(3)%raw = ''
            color(4)%raw = ''
            color(5)%raw = ''
        end if

    end subroutine set_terminal

    !> 黄色
    pure function yellow(msg) result(ans)
        character(*), intent(in) :: msg     !! Input message <br>
                                            !! 输入信息
        character(:), allocatable :: ans

        ans = color(3)%raw//msg//color(5)%raw

    end function yellow

    !> 蓝色
    pure function blue(msg) result(ans)
        character(*), intent(in) :: msg     !! Input message <br>
                                            !! 输入信息
        character(:), allocatable :: ans

        ans = color(4)%raw//msg//color(5)%raw

    end function blue

    !> 红色
    pure function red(msg) result(ans)
        character(*), intent(in) :: msg     !! Input message <br>
                                            !! 输入信息
        character(:), allocatable :: ans

        ans = color(1)%raw//msg//color(5)%raw

    end function red

    !> 绿色
    pure function green(msg) result(ans)
        character(*), intent(in) :: msg     !! Input message <br>
                                            !! 输入信息
        character(:), allocatable :: ans

        ans = color(2)%raw//msg//color(5)%raw

    end function green

end module sph_terminal
